package com.chenss.dragonser.activity;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.ArrayMap;
import android.support.v7.widget.CardView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chenss.dragonser.R;
import com.chenss.dragonser.app.AppInfo;
import com.chenss.dragonser.app.Constant;
import com.chenss.dragonser.base.BaseActivity;
import com.chenss.dragonser.network.NetworkRequest;
import com.chenss.dragonser.network.RequestCallbcak;
import com.chenss.dragonser.response.OrderDetailResponse;
import com.chenss.dragonser.utils.GsonUtil;
import com.chenss.dragonser.utils.ToastUtil;

import org.json.JSONException;

import java.util.logging.Logger;

/**
 * PageName: 订单详情
 * Create by chenss at 2018/4/20 2:54
 */
public class OrderDetailInfoActivity extends BaseActivity implements RequestCallbcak {
    LinearLayout ll_left;//左边按钮
    TextView tv_page_title;
    int status = 0;
    TextView tv_bottom, tv_bottom_btn;//底部
    TextView tv_username, tv_mobile, tv_addr;
    TextView tv_all, tv_all_price;
    TextView tv_sale_num;
    TextView tv_mark;
    TextView tv_point1, tv_point2, tv_point3;
    TextView tv_point_tip1, tv_point_tip2, tv_point_tip3;
    ImageView img_point1, img_point2, img_point3;
    LinearLayout ll_goods;

    TextView tv_express_price, tv_express_no, tv_time;
    CardView card_send;//配送详情

    String orderId = "";
    public NetworkRequest networkRequest;//网络请求
    public ArrayMap<String, String> parmMap;//请求参数封装

    @Override
    public void initParms(Bundle parms) {
        status = getIntent().getExtras().getInt("status", 0);
        orderId = getIntent().getExtras().getString("orderId");
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_order_detail_ifno;
    }

    @Override
    public void initView(View view) {
        ll_left = findView(R.id.ll_left);//左边按钮
        tv_page_title = findView(R.id.tv_page_title);
        ll_left.setVisibility(View.VISIBLE);
        ll_left.setOnClickListener(this);
        tv_page_title.setText("订单详情");

        card_send = findView(R.id.card_send);
        ll_goods = findView(R.id.ll_goods);
        tv_bottom = findView(R.id.tv_bottom);
        tv_bottom_btn = findView(R.id.tv_bottom_btn);
        tv_username = findView(R.id.tv_username);
        tv_mobile = findView(R.id.tv_mobile);
        tv_addr = findView(R.id.tv_addr);

        tv_mark = findView(R.id.tv_mark);
        tv_all = findView(R.id.tv_all);
        tv_all_price = findView(R.id.tv_all_price);
        tv_point1 = findView(R.id.tv_point1);
        tv_point2 = findView(R.id.tv_point2);
        tv_point3 = findView(R.id.tv_point3);

        tv_point_tip1 = findView(R.id.tv_point_tip1);
        tv_point_tip2 = findView(R.id.tv_point_tip2);
        tv_point_tip3 = findView(R.id.tv_point_tip3);

        tv_express_price = findView(R.id.tv_express_price);
        tv_express_no = findView(R.id.tv_express_no);
        tv_time = findView(R.id.tv_time);
        tv_sale_num = findView(R.id.tv_sale_num);

        img_point1 = findView(R.id.img_point1);
        img_point2 = findView(R.id.img_point2);
        img_point3 = findView(R.id.img_point3);

    }

    @Override
    public void doBusiness(Context context) {
        networkRequest = new NetworkRequest(this, this);
        getDetailsInfoDatas();
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.ll_left:
                finish();
                break;
        }
    }

    /**
     * 获取信息
     */
    private void getDetailsInfoDatas() {
        /* 修改这里 - 下方为接口所要传递的参数 */
//        'userid' => '938a40b513f443b486ec880dee5422f6', // 纬度
//                'order_id' => 'JCA08ff04d99a5e70d7afcc74e0477', // 订单id
        parmMap = new ArrayMap<>();
        Constant.setCommonParams(parmMap, Constant.App.Order, Constant.classes.Order_an_OrderInfo);
        parmMap.put("storehouse_id", AppInfo.getUser(this).getStorehouse_id());
        parmMap.put("userid", "0");
        parmMap.put("order_id", orderId);

        networkRequest.postJsonRequest(Constant.serverPath, parmMap, Constant.Actionid.NETWORK_REQUEST_CODE_1, true, Constant.classes.Order_an_OrderInfo);
    }

    /**
     * 确认发货
     */
    private void subSendGoods(String orderId, String remark, String freight_money, String logistics_no) {
        /* 修改这里 - 下方为接口所要传递的参数 */
//        'storehouse_id' => '', // 门店唯一id
//                'order_id' => '', //
//                'freight_money' => '10', //物流金额
//                'logistics_no' => '1', //物流单号
//                'remark' => '1', //备注
        parmMap = new ArrayMap<>();
        Constant.setCommonParams(parmMap, Constant.App.Order, Constant.classes.Order_an_ServeOrderConfirm);
        parmMap.put("storehouse_id", AppInfo.getUser(this).getStorehouse_id());//服务站用户id
        parmMap.put("order_id", orderId);
        parmMap.put("store_id", AppInfo.getUser(this).getStore_id());
        parmMap.put("freight_money", freight_money);
        parmMap.put("logistics_no", logistics_no);
        parmMap.put("remark", remark);
        networkRequest.postJsonRequest(Constant.serverPath, parmMap, Constant.Actionid.NETWORK_REQUEST_CODE_2, true, Constant.classes.Order_an_ServeOrderConfirm);
    }

    @Override
    public void onFaild(int orderCode, String result) {
        ToastUtil.showShort(this, result);
    }

    @Override
    public void onSucceed(int orderCode, String result) throws JSONException {
        Logger.getLogger(result);
        if (orderCode == Constant.Actionid.NETWORK_REQUEST_CODE_1) {
            OrderDetailResponse detailResponse = GsonUtil.GsonToBean(result, OrderDetailResponse.class);
            if (null != detailResponse) {

                if (null != detailResponse.getData().getOrder_info()) {

                    if (detailResponse.getData().getOrder_info().getOrder_status().equals("2")) {
                        //待发货
                        card_send.setVisibility(View.GONE);
                        tv_bottom_btn.setText("确认发货");
                        tv_bottom_btn.setBackgroundColor(ContextCompat.getColor(OrderDetailInfoActivity.this, R.color.appColor));
                        final String orderId = detailResponse.getData().getOrder_id();
                        tv_bottom_btn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                showSendGoodsDialog(orderId);
                            }
                        });
                    } else if (detailResponse.getData().getOrder_info().getOrder_status().equals("3")) {
                        card_send.setVisibility(View.VISIBLE);
                        tv_bottom_btn.setText("等待买家收货");
                        tv_bottom_btn.setBackgroundColor(ContextCompat.getColor(OrderDetailInfoActivity.this, R.color.textLightGray));
                    } else if (detailResponse.getData().getOrder_info().getOrder_status().equals("4")) {
                        card_send.setVisibility(View.VISIBLE);
                        tv_bottom_btn.setText("买家已收货");
                        tv_bottom_btn.setBackgroundColor(ContextCompat.getColor(OrderDetailInfoActivity.this, R.color.textLightGray));
                    } else if (detailResponse.getData().getOrder_info().getOrder_status().equals("5")) {
                        card_send.setVisibility(View.VISIBLE);
                        tv_bottom_btn.setText("已完成");
                        tv_bottom_btn.setBackgroundColor(ContextCompat.getColor(OrderDetailInfoActivity.this, R.color.textLightGray));
                    }
                    tv_username.setText(detailResponse.getData().getOrder_info().getReceiver_name());
                    tv_mobile.setText(detailResponse.getData().getOrder_info().getReceiver_phone());
                    tv_addr.setText(detailResponse.getData().getOrder_info().getReceiver_address());
                    tv_all_price.setText("￥" + detailResponse.getData().getOrder_info().getTotal_money() + "");
//                    tv_goosName.setText(detailResponse.getData().getOrder_info().getOrder_goods().get(0).getGoods_name());
//                    tv_goodsPrice.setText("￥" +detailResponse.getData().getOrder_info().getOrder_goods().get(0).getSale_price());
                    double all = Double.parseDouble(detailResponse.getData().getOrder_info().getOrder_goods().get(0).getSale_price()) * Integer.parseInt(detailResponse.getData().getOrder_info().getOrder_goods().get(0).getSale_num());
                    tv_all.setText("￥" + all);
//                    tv_count.setText("x"+detailResponse.getData().getOrder_info().getOrder_goods().get(0).getSale_num());
                    tv_sale_num.setText("总数：" + detailResponse.getData().getOrder_info().getBuy_count());
                    if (Double.parseDouble( detailResponse.getData().getOrder_info().getCashcoupon_deductible_total()) == 0) {
                        img_point3.setImageResource(R.mipmap.icon_point_2);
                        tv_point3.setTextColor(ContextCompat.getColor(this, R.color.textLightGray));
                        tv_point_tip3.setTextColor(ContextCompat.getColor(this, R.color.textLightGray));
                        tv_point3.setText("未使用");
                    } else {
                        img_point3.setImageResource(R.mipmap.icon_point_1);
                        tv_point3.setTextColor(ContextCompat.getColor(this, R.color.appColor));
                        tv_point_tip3.setTextColor(ContextCompat.getColor(this, R.color.appColor));
                        tv_point3.setText("￥" +  detailResponse.getData().getOrder_info().getCashcoupon_deductible_total());
                    }
                    if (Double.parseDouble( detailResponse.getData().getOrder_info().getCoupon_deductible_total()) == 0) {
                        img_point2.setImageResource(R.mipmap.icon_point_2);
                        tv_point2.setTextColor(ContextCompat.getColor(this, R.color.textLightGray));
                        tv_point_tip2.setTextColor(ContextCompat.getColor(this, R.color.textLightGray));
                        tv_point2.setText("未使用");

                    } else {
                        img_point2.setImageResource(R.mipmap.icon_point_1);
                        tv_point2.setTextColor(ContextCompat.getColor(this, R.color.appColor));
                        tv_point_tip2.setTextColor(ContextCompat.getColor(this, R.color.appColor));
                        tv_point2.setText("￥" +  detailResponse.getData().getOrder_info().getCoupon_deductible_total());
                    }
                    String useBalance =  detailResponse.getData().getOrder_info().getUse_balance();
                    if (!TextUtils.isEmpty(useBalance) && Double.parseDouble(useBalance) > 0) {
                        img_point1.setImageResource(R.mipmap.icon_point_1);
                        tv_point1.setTextColor(ContextCompat.getColor(this, R.color.appColor));
                        tv_point_tip1.setTextColor(ContextCompat.getColor(this, R.color.appColor));
                        tv_point1.setText("￥" + useBalance);
                    } else {
                        img_point1.setImageResource(R.mipmap.icon_point_2);
                        tv_point1.setTextColor(ContextCompat.getColor(this, R.color.textLightGray));
                        tv_point_tip1.setTextColor(ContextCompat.getColor(this, R.color.textLightGray));
                        tv_point1.setText("未使用");
                    }
                    tv_express_no.setText(detailResponse.getData().getOrder_info().getLogistics_no());
                    tv_express_price.setText(detailResponse.getData().getOrder_info().getFreight_money());
                    tv_time.setText(detailResponse.getData().getOrder_info().getDelivery_time());
                    if (!TextUtils.isEmpty(detailResponse.getData().getOrder_info().getBuyer_note())) {
                        tv_mark.setText("备注：" + detailResponse.getData().getOrder_info().getBuyer_note());
                    } else {
                        tv_mark.setText("备注：无");
                    }


                    ll_goods.removeAllViews();
                    if (null != detailResponse.getData().getOrder_info().getOrder_goods()) {
                        int size = detailResponse.getData().getOrder_info().getOrder_goods().size();
                        for (int i = 0; i < size; i++) {
                            View view = LayoutInflater.from(this).inflate(R.layout.item_frag_order_child, null);
                            ImageView img = (ImageView) view.findViewById(R.id.goodsImg);
                            TextView tv_name = (TextView) view.findViewById(R.id.tv_goodsName);
                            TextView tv_price = (TextView) view.findViewById(R.id.tv_goodsPrice);
                            TextView tv_count = (TextView) view.findViewById(R.id.tv_bugCount);
                            tv_name.setText(detailResponse.getData().getOrder_info().getOrder_goods().get(i).getGoods_name());
                            tv_count.setText("x" + detailResponse.getData().getOrder_info().getOrder_goods().get(i).getSale_num());
                            tv_price.setText("￥" + detailResponse.getData().getOrder_info().getOrder_goods().get(i).getSale_price());

                            if (!TextUtils.isEmpty(detailResponse.getData().getOrder_info().getOrder_goods().get(i).getGoods_image())) {
                                Glide.with(this).load(detailResponse.getData().getOrder_info().getOrder_goods().get(i).getGoods_image()).into(img);
                            }

                            view.setTag(detailResponse.getData().getOrder_info().getOrder_goods().get(i).getContent_id());
                            ll_goods.addView(view);
                        }
                    }
                }

            }


        } else if (orderCode == Constant.Actionid.NETWORK_REQUEST_CODE_2) {
            ToastUtil.showShort(this, "发货成功");
//发货成功
            getDetailsInfoDatas();
        }
    }

    /**
     * 确认发货提示框
     */
    protected void showSendGoodsDialog(final String orderId) {
        final Dialog dialog = new Dialog(this, R.style.Dialog_image);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_input_express);
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        final EditText edt = (EditText) dialog.findViewById(R.id.edt_price);
        final EditText edt_order = (EditText) dialog.findViewById(R.id.edt_order);
        TextView tv_title = (TextView) dialog.findViewById(R.id.tv_title);
        Button btn_qx = (Button) dialog.findViewById(R.id.btn_one);
        Button btn_qd = (Button) dialog.findViewById(R.id.btn_two);
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.CENTER);
        if (!dialog.isShowing()) {
            dialog.show();
        }

        dialog.getWindow().setAttributes(params);
        edt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        edt.setText(s);
                        edt.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    edt.setText(s);
                    edt.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        edt.setText(s.subSequence(0, 1));
                        edt.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
judgeNumber(s);
            }

        });
        btn_qx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();

            }
        });
        btn_qd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (TextUtils.isEmpty(edt.getText().toString())) {
                    ToastUtil.showShort(OrderDetailInfoActivity.this, "请输入运费");
                    return;
                }
                if (TextUtils.isEmpty(edt_order.getText().toString())) {
                    ToastUtil.showShort(OrderDetailInfoActivity.this, "请输入运单号");
                    return;
                }
//                ToastUtil.showShort(this, "发货成功");
                dialog.dismiss();

                subSendGoods(orderId, "无", edt.getText().toString(), edt_order.getText().toString());
            }
        });

    }
    /**
     * 金额输入框中的内容限制（最大：小数点前五位，小数点后2位）
     * @param edt
     */
    public void judgeNumber(Editable edt){

        String temp = edt.toString();
        int posDot = temp.indexOf(".");//返回指定字符在此字符串中第一次出现处的索引
        if (posDot <= 0) {//不包含小数点
            if (temp.length() <= 3) {
                return;//小于五位数直接返回
            } else {
                edt.delete(3, 4);//大于五位数就删掉第六位（只会保留五位）
                return;
            }
        }
        if (temp.length() - posDot - 1 > 2)//如果包含小数点
        {
            edt.delete(posDot + 3, posDot + 4);//删除小数点后的第三位
        }
    }
}
